package com.pine.app.module.security.oauth.provider.token;


import com.alibaba.fastjson.JSON;
import com.pine.app.module.security.oauth.provider.OAuth2ClientRequest;
import com.pine.app.module.security.oauth.provider.OAuth2Authentication;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author xiaoyuan
 * @create 2019/10/8 14:28
 **/
public class DefaultAuthenticationKeyGenerator implements AuthenticationKeyGenerator {
    private static final String CLIENT_ID = "client_id";
    private static final String SCOPE = "scope";
    private static final String USERNAME = "username";

    public DefaultAuthenticationKeyGenerator() {
    }

    public String extractKey(OAuth2Authentication authentication) {
        Map<String, String> values = new LinkedHashMap();
        OAuth2ClientRequest authorizationRequest = authentication.getTokenRequest();
        if(!authentication.isClientOnly()) {
            values.put("username", authentication.getUserDetails().getUsername());
        }

        values.put("client_id", authorizationRequest.getClientId());
        if(authorizationRequest.getScope() != null) {
            values.put("scope", JSON.toJSONString(authentication.getTokenRequest().getScope()));
        }

        return this.generateKey(values);
    }

    protected String generateKey(Map<String, String> values) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] bytes = digest.digest(values.toString().getBytes("UTF-8"));
            return String.format("%032x", new Object[]{new BigInteger(1, bytes)});
        } catch (NoSuchAlgorithmException var4) {
            throw new IllegalStateException("MD5 algorithm not available.  Fatal (should be in the JDK).", var4);
        } catch (UnsupportedEncodingException var5) {
            throw new IllegalStateException("UTF-8 encoding not available.  Fatal (should be in the JDK).", var5);
        }
    }
}
